package cn.growthgate.fgo.util;

import java.security.Provider;
import java.security.Provider.Service;
import java.security.Security;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

/**
 * 加密工具类
 * 
 * @author GrowthGate
 * @since 2019年1月23日
 *
 */
public class SecretUtils {

	/** 默认加密次数 */
	public static final int DEFAULT_ITERATION_COUNT = 1096;
	/** 默认密文长度 */
	public static final int DEFAULT_LENGTH = 128;

	/**
	 * PBKDF2WithHmacSHA512
	 * 
	 * @param srcStr
	 * @param salt
	 * @return
	 */
	public static String pbkdf2WithHmacSHA512(String srcStr, String salt) {
		return pbkdf2WithHmacSHA512(srcStr, salt, DEFAULT_ITERATION_COUNT, DEFAULT_LENGTH);
	}

	/**
	 * PBKDF2WithHmacSHA512
	 * 
	 * @param srcStr
	 *            要加密的内容
	 * @param salt
	 *            盐值
	 * @param iterationCount
	 *            重复加密次数
	 * @param length
	 *            密文长度
	 * @return
	 */
	public static String pbkdf2WithHmacSHA512(String srcStr, String salt, int iterationCount, int length) {
		if (srcStr == null || salt == null) {
			return null;
		}
		try {
			SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
			PBEKeySpec ks = new PBEKeySpec(srcStr.toCharArray(), salt.getBytes(), iterationCount, length * 4);
			SecretKey sk = skf.generateSecret(ks);
			return HashUtils.toHex(sk.getEncoded());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取Java支持的所有加密算法
	 */
	public static void getServices() {
		for (Provider provider : Security.getProviders()) {
			System.out.println("===================" + provider.getName() + "===================");
			for (Service service : provider.getServices()) {
				System.out.println();
				System.out.println(service);
			}
			System.out.println();
		}
	}

}
